mui.init({
	preloadPages:[{
		id:'mobile_register',
		url:'../register/register.html'
	}],
	beforeback: function(){
//		alert(plus.webview.getLaunchWebview().id);
//		var indexPage = plus.webview.getLaunchWebview();
//		var indexPageId = indexPage.id;
//		mui.fire(indexPage,'refresh',{});
		return true;
	}
});

var old_back = mui.back;
mui.back = function(){
	    	plus.webview.currentWebview().hide();
	    var targetPageId =	plus.storage.getItem(KeyCfg.targetPageId);
	    var targetPage = null;
	    window.setTimeout(function(){
	    		if(targetPageId){
				targetPage = plus.webview.getWebviewById(targetPageId);    	
		    }
		    if(!targetPage) targetPage = plus.webview.getLaunchWebview();
		    targetPage.show();
			var currClickTabId = plus.storage.getItem(KeyCfg.currClickTabId);
			if(!currClickTabId || currClickTabId == "userAccount")	 currClickTabId = "defaultTab";
		    plus.storage.setItem(KeyCfg.currClickTabId,currClickTabId);/*点击返回按钮，则默认到首页*/
		    mui.fire(targetPage,'refresh',{});
	    },250);
}

/**
 * 当从登录页面返回时，回调用当前“刷新”事件 
 */
window.addEventListener('refresh',function(event){
	resetForm();
});

/**
 * 当从登录页面返回时，回调用当前“刷新”事件 
 */
window.addEventListener('reload',function(event){
	resetForm();
});


function resetForm(){
	FormMgr.resetFields(["userName","pwd"],true); /*清空密码字段*/
	$("#pwd").val('');
	setValue();
}

function setValue(){
	var userName = plus.storage.getItem(KeyCfg.userName);
	if(!userName) return;
	var ele = $('#userName');
	ele.css({"color":"black","font-size":"14px"});
	ele.val(userName);
}

mui.plusReady(function() {
	resetForm();
 	//setValue();
 	
 	var btnLogin = CmwMcore.$('btn_login');
	MeventMgr.onTouchstart(btnLogin,function(event,self){
		if(!valid()) return;
		$.ajax(UrlConfig.checkLoginStatus,{  
	        data : {userName:$('#userName').val()},  
	        dataType : 'jsonp',  
	        crossDomain: true,  
	        success: function(data) {
	        	data = JSON.parse(data);
	        	if(data.flag==0){
	        		submitForm();
	        	}else if(data.flag==1){
	        		mui.confirm('您的账号已在PC端登陆，在手机登录将会踢出PC端！','来理财', {
						'确定': 'ok',
						'取消': 'no'
					},function(e){
						if(e.index == 0){
							submitForm();
						}
					});
	        	}else if(data.flag==2){
	        		mui.alert("用户名不存在！");
	        	}
	        },
	        error :function(){
	        	
	        }
	    });
	});
	
	var btnRegister = CmwMcore.$('btn_register');
	MeventMgr.onTouchstart(btnRegister,function(event,self){
		var loginPageId = plus.webview.currentWebview().id;
		plus.storage.setItem(KeyCfg.loginPageId,loginPageId);
		var cfg = {id:'mobile_register',pars :{}};
		MuiEventMgr.open('../register/register.html',cfg);
		var targetPage = plus.webview.getWebviewById('mobile_register');
		if(targetPage) mui.fire(targetPage,'refresh',{});
		return false;
	});
	
	/*------ 忘记密码 ------*/
	var forget_pwd = CmwMcore.$('forget_pwd');
	MeventMgr.onTouchstart(forget_pwd,function(event,self){
		MuiEventMgr.open('../resetpwd/userName.html',{});
		return false;
	});
	
	/*表单验证*/
	function valid(){
		var eleUserName = $('#userName');
		var elePwd = $('#pwd');
		var userName_val = eleUserName.val();
		var pwd_val = elePwd.val();
		var uerName_emptyText = eleUserName.attr("placeholder");
		var pwd_emptyText = elePwd.attr("placeholder");
		if(!userName_val || userName_val.trim() == uerName_emptyText){
			eleUserName.focus();
			mui.alert("请输入用户名/手机号码!");
			return false;
		}
		
		if(!pwd_val || pwd_val.trim() == pwd_emptyText){
			elePwd.focus();
			mui.alert("请输入密码!");
			return false;
		}
		return true;
	}
	
	function submitForm(){
		CmwMcore.disabled('btn_login');
		var formDatas = $("#theForm").serialize();
		var url = UrlConfig.muser_login;
		$.ajax(url, {  
	        data : formDatas,  
	        dataType : 'jsonp',  
	        crossDomain: true,  
	        success: function(data) {
	        	data = JSON.parse(data);
	        	callback(data);
	        	window.location.reload();
	        },
	        error :function(){
	        		CmwMcore.enabled('btn_login');
	        }
	    });
	}
	
	function callback(data){
		var success = data.success;
		var msg = data.msg;
		if(!success){
			mui.alert(msg);
			return;
		}
		saveData(data);
		forward();
		resetForm();
	}
	
	
	/**
	 * 保存数据到 storage 中 
	 * @param {Object} data 要保存的用户数据
	 */
	function saveData(data){
		var sessionId = data[KeyCfg.JSESSIONID];
		var userId = data[KeyCfg.userId];
		var userName = data[KeyCfg.userName];
		plus.storage.setItem(KeyCfg.JSESSIONID, sessionId);
		plus.storage.setItem(KeyCfg.userId, userId);
		plus.storage.setItem(KeyCfg.userName, userName);
		plus.storage.setItem(KeyCfg.userPwd,$("#pwd").val());
		var settings = app.getSettings();
		settings.gestures = data[KeyCfg.lockPassword];
		settings.autoLogin = true;
		var date = new Date();
		settings.overTime = date.getTime();
		app.setSettings(settings);
	}
	
	/**
	 * 登录成功后跳转   
	 */
	function forward(){
//		var _this = plus.webview.currentWebview();
//		var url = "../../index.html";
//		var pars = {};
// 		var prevUrl = plus.storage.getItem(KeyCfg.prevUrl);/*上一目标页面*/
// 		console.log("prevUrl="+prevUrl);
// 		if(prevUrl){
// 			url = prevUrl;
// 			var prevParsStr = plus.storage.getItem(KeyCfg.prevPars);/*上一页面参数*/
// 			if(prevParsStr){
// 				pars = JSON.parse(prevParsStr);
// 			}
// 			var cfg = {pars : pars};
//			MuiEventMgr.open(url,cfg);
//			plus.storage.removeItem(KeyCfg.prevPars);
// 		}else{
// 			login/login.html
//			refreshParentPage();
//   		mui.back();
// 			plus.webview.currentWebview().parent().evalJS("activeTabItemPage('userAccount');");
// 		}
		var win = plus.webview.getWebviewById(appid);
 		win.evalJS("openTab(null,subpages[2]);refreshSubPages('userAccount');");
	}
	
	/**
	 * 刷新父页面，参见 index.js 第 76 号代码 
	 */
	function refreshParentPage(){
		var targetPageId = plus.storage.getItem(KeyCfg.targetPageId);
		if(!targetPageId) return;
		var targetPage = plus.webview.getWebviewById(targetPageId);
		mui.fire(targetPage,'refresh',{});
	}
});
